import logging

from django.contrib.contenttypes.models import ContentType

from apps.system.models import OperationRecord

logger = logging.getLogger("myapp")


from django.contrib.auth.models import AnonymousUser

class LogMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        # 请求参数
        if request.method == "GET":
            params = request.GET.urlencode()
        elif request.method == "POST":
            params = request.POST.urlencode()
        else:
            params = ""

        if not isinstance(request.user, AnonymousUser):
            user = request.user
            # user = f"{request.user.name}"
        else:
            user = None

        url_name = request.resolver_match.url_name if request.resolver_match else None

        if user is  None:
            pass
        else:
            content_type = ContentType.objects.get_for_model(request.user)
            log = OperationRecord(
                content_type=content_type,
                object_id=request.user.pk,
                content_object=request.user,
                user=user,
                request_method=request.method,
                request_path=request.path,
                request_params=params,
                url_name=url_name,
                response_status=response.status_code
            )
            log.save()
        logger.info(
            f"user: {user}, Request method: {request.method}, path: {request.path}, url name: {url_name}, Response status: {response.status_code}")

        return response